<?php

namespace dragon\Wechat;

use app\api\controller\TimerController;
use dragon\Exceptions\WechatException;
use dragon\Support\Wechat as WechatSend;
use dragon\Company\SysConfig;
use dragon\Company\Entity\CompanyUser;
use think\Db;

class WechatMessage
{
    const ORDER_NOTICE = 1;
    const BALANCE_MSG = 2;
    const PATH = 'http://wechat.yibuxinxi.com/';

    // 模板类型
    public static $templateType = [
        '1' => '订单通知',
        '2' => '余额不足通知',
    ];

    public static function orderNotify($order)
    {
        // 接收人
        $map = ['u.company_id' => $order->client_id];
        $listener = CompanyUser::alias('u')
            ->join('third_party_user t', 'u.user_id = t.user_id')
            ->where($map)
            ->field('u.id, u.role_id, t.openid')
            ->select();

        $data = [
            'first' => OrderLogic::$statusConfig[$order->status] . '通知!',
            'keyword1' => $order->carrier_name,
            'keyword2' => $order->carrier_mobile,
            'keyword3' => date('Y-m-d H:i:s', $order->create_time),
            'remark' => '物品总数：' . $order->num . ', 点击查看详情',
        ];

        foreach ($data as $k => $v) {
            $data[$k] = array(
                'value' => $v,
                'color' => '#173177',
            );
        }
        $order->isTakeOrder() ? $param = 'takeOrder?take_order_no=' : $param = 'deliverOrder?deliver_order_no=';
        $list = [];
        foreach ($listener as $k => $v) {
            $list[$k]['send'] = [
                'touser' => $v['openid'],
                'template_id' => 'RZE7mtbg7lBJHQmggDoup3aA_kObomEMVQE9og72PT8',
                'url' => WechatMessage::PATH . 'Hotel/tasklist.html',
                'topcolor' => '#ff0000',
                'data' => $data,
            ];
            $list[$k]['save'] = [
                'type' => WechatMessage::ORDER_NOTICE,
                'company_user_id' => $v['id'],
                'data' => json_encode($data),
                'url' => WechatMessage::PATH . 'Hotel/tasklist.html',
                'response' => '',
                'status' => 0,

            ];
        }

        static::send($list);
    }

    // 余额不足模板消息
    public static function balanceMsg($company)
    {
        // 接收人
        $map['u.company_id'] = $company->id;
        switch ($company->type) {
            case 1:
                $map['u.role_id'] = SysConfig::FACTORY_MASTER;
                $action = 'Factory/';
                break;
            case 2:
                $map['u.role_id'] = SysConfig::HOTEL_MASTER;
                $action = 'Hotel/';
                break;
            default:
                return false;
        }

        $listener = CompanyUser::alias('u')
            ->join('third_party_user t', 'u.user_id = t.user_id')
            ->where($map)
            ->field('u.id, u.role_id, t.openid')
            ->select();

        $data = [
            'first' => '余额不足通知!',
            'keyword1' => $company->title,
            'keyword2' => $company->account->balance,
            'remark' => '感谢你的使用',
        ];

        foreach ($data as $k => $v) {
            $data[$k] = array(
                'value' => $v,
                'color' => '#173177',
            );
        }
        $list = [];
        foreach ($listener as $k => $v) {
            $list[$k]['send'] = [
                'touser' => $v['openid'],
                'template_id' => 'ekAG0OvEJ60lyNMR8MixrX3RACqlLZYHjxhPBvV-U2c',
                'url' => WechatMessage::PATH . $action . 'rechargeRecords.html',
                'topcolor' => '#ff0000',
                'data' => $data,
            ];
            $list[$k]['save'] = [
                'type' => WechatMessage::BALANCE_MSG,
                'company_user_id' => $v['id'],
                'data' => json_encode($data),
                'url' => WechatMessage::PATH . $action . 'rechargeRecords.html',
                'response' => '',
                'status' => 0,

            ];
        }

        static::send($list);
    }

    public static function send($data)
    {
        // 发送
        $data = static::iSend($data);
        // 记录发送记录
        foreach ($data as $k => $v) {
            Db::name('wechat_message')->insert($v['save']);
        }
    }

    // 延时发送
    public static function delaySend()
    {
        // 插入数据库
        // 修改状态
    }

    // 计时器
    public static function timer()
    {
        $map = [];
        $map['status'] = 0;
        $map['create_time'] = ['<', TimerController::getUpdateTime()];

        $data = Db::name('wechat_message')
            ->where($map)
            ->select();
        // 发送
        static::timerSend($data);
    }


    // 计时发送
    public function timerSend($data)
    {
        $wechat = WechatSend::instance('sdk');
        $list = [];
        foreach ($data as $k => $v) {
            $list = [
                'touser' => $v['company_user_id'],
                'template_id' => 'mRvFAHd8tc21LMH5P3IK6EyD1ork-5XRNsYC5GENFRc',
                'url' => $v['url'],
                'topcolor' => '#ff0000',
                'data' => json_decode($data),
            ];
            $response = $wechat->sendTemplateMessage($list);
            $result = Db::name('wechat_message')
                ->where('id', $v['id'])
                ->update(['response' => json_encode($response), 'status' => 1]);
            if ($result === false) throw  new WechatException();
        }

    }


    public static function iSend($data)
    {
        // 即时发送
        $wechat = WechatSend::instance('sdk');
        foreach ($data as $k => $v) {
            $response = $wechat->sendTemplateMessage($v['send']);
            $data[$k]['save']['response'] = json_encode($response);
            $data[$k]['save']['status'] = 1;
        }
        return $data;
    }


}
